<template>
    <div class="users">
        <!-- 搜索模块 -->
        <div class="search">
            <el-select
                       v-model="searchText"
                       filterable
                       clearable
                       reserve-keyword
                       remote
                       loading-text="正在加载..."
                       no-match-text="查询不到数据"
                       no-data-text="没有数据"
                       placeholder="输入要查找的用户名"
                       default-first-option
                       :remote-method="handleSearch"
                       @focus="handleSearchInputFocus"
                       @change="searchChange"
                       :loading="searchLoading">
                <el-option
                           v-for="item in searchOptions"
                           :key="item.username"
                           :value="item.username" />
            </el-select>
        </div>
        <!-- 批量操作和添加 -->
        <div class="collaction">
            <el-button type="primary" @click="addUser">添加用户</el-button>
            <el-button type="success" plain>
                <template #icon>
                    <svg class="icon">
                        <use xlink:href="#icon-excel"></use>
                    </svg>
                </template>
                <template #default>导出选中数据</template>
            </el-button>
            <el-button type="warning" plain>
                <template #icon>
                    <svg class="icon">
                        <use xlink:href="#icon-excel"></use>
                    </svg>
                </template>
                <template #default>导出全部</template>
            </el-button>
        </div>
        <el-table :data="tableData" :row-key="row => row.unid" v-loading="tableLoading" style="width: 100%">
            <el-table-column reserve-selection align="center" type="selection" label="选择"></el-table-column>
            <el-table-column align="center" prop="username" label="用户名">
                <template #default="{ row }">
                    <el-tag
                            size:="large"
                            class="mx-2"
                            type="success"
                            effect="dark"
                            round>
                        {{ row.username }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="nickname" label="昵称">
                <template #default="{ row }">
                    <el-tag
                            size:="large"
                            class="mx-2"
                            type="info"
                            effect="dark"
                            round>
                        {{ row.nickname }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="phone" label="手机号">
            </el-table-column>
            <el-table-column align="center" prop="roleName" label="角色名称">
                <template #default="{ row }">
                    <el-tag
                            size:="large"
                            class="mx-1"
                            effect="dark"
                            round>
                        {{ row.roleName }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column width="200" align="center" prop="create_at" label="创建时间">
                <template #default="{ row }">
                    <el-tag
                            size:="large"
                            class="mx-1"
                            type="warning"
                            effect="dark"
                            round>
                        {{ row.create_at }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="sex" width="60" label="性别">
                <template #default="{ row }">
                    <b v-if="row.sex == 1">男</b>
                    <b v-else>女</b>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="status" label="用户状态">
                <template #default="{ row }">
                    <el-switch
                               :loading="row.switchLoading"
                               :disabled="disabledSwitch(row.roleid)"
                               size="large"
                               v-model="row.status"
                               active-value="1"
                               inactive-value="0"
                               class="ml-2"
                               @change="changeUserStatus(row)"
                               inline-prompt
                               style="--el-switch-on-color: #077ed3; --el-switch-off-color: #ff4949"
                               active-text="启用"
                               inactive-text="禁用" />
                </template>
            </el-table-column>
            <el-table-column width="300" label="操作">
                <template #default="{ row }">
                    <!-- <el-dropdown trigger="click" type="primary">
                    <el-button type="primary">
                        操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item>
                                <el-button type="primary" size="small" @click="assigmentRole(row)">分配角色</el-button>
                            </el-dropdown-item>
                            <el-dropdown-item>
                                <el-button>编辑</el-button>
                            </el-dropdown-item>
                            <el-dropdown-item>
                                <el-button type="danger">删除</el-button>
                            </el-dropdown-item>
                        </el-dropdown-menu> -->
                    <!-- </template>
                </el-dropdown> -->
                    <el-button type="primary" v-access="row.roleid" plain @click="openEditDialog(row)">编辑</el-button>
                    <el-button type="danger" v-access="row.roleid" plain @click="deleteUser(row)">删除</el-button>
                    <el-button type="primary" v-access="row.roleid" @click="assignmentRole(row)">分配角色</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog width="30%" center v-model="showDialog" title="分配角色">
            <div class="select-user">
                <b>当前分配的用户:</b>
                <el-tag
                        type="danger"
                        size="large"
                        class="ml-2">
                    {{ targetUsername }}
                </el-tag>
            </div>
            <el-select v-model="selectRoleid" placeholder="选择角色">
                <el-option

                           v-for="item in roleOptions"
                           :key="item.roleid"
                           :label="item.roleName"
                           :value="item.roleid"
                           :disabled="item.disabled" />
            </el-select>

            <template #footer>
                <el-button type="primary" @click="handleAssignmentConfirm">确定</el-button>
                <el-button type="danger" @click="handleAssignmentCancel">取消</el-button>
            </template>
        </el-dialog>
        <!-- 分页器 -->
        <div class="pagenation">
            <el-pagination background layout="prev, pager, next" @current-change="handlePageSizeChange"
                           :current-page="fetchTableListParam.page"
                           hide-on-single-page
                           :page-size="fetchTableListParam.count" :total="total" />
        </div>
        <uDialog @ok="updateUser" v-model="showEditDialog" :title="title" :reviewData="reviewData" :action="action">
        </uDialog>
    </div>
</template>

<script setup>
import disabledSwitch from "@/utils/disabledSwitch"
import uDialog from "@/components/uDialog/index.vue"
import { ArrowDown } from '@element-plus/icons-vue'
import { ref, onMounted, reactive, h } from "vue"

import { getUsersListApi, updateUserApi, addUserApi, deleteUserApi } from "../../api/users";

import sDrawer from "../sDrawer/index.vue"
import { ElMessage, ElMessageBox } from "element-plus";

import * as roleApi from "@/api/role"

//引入roleStore

import useRole from "@/store/role"

//引入判断是否是子节点的方法

import isChild from "@/utils/isChild"

//把用户的store引入

import useUser from "@/store/users"

//使用角色store

let roleStore = useRole()

//使用用户store

let userStore = useUser()

//声明控制dialog打开和关闭的方法

let showDialog = ref(false)

//声明控制抽屉的变量

let showDrawer = ref(true)

//声明switch的loading

let switchLoading = ref(false)

//表格的数据
let tableData = ref([])

//控制加载动画的变量

let tableLoading = ref(false)
//封装一个获取用户列表的方法

let getUsersList = async () => {

    tableLoading.value = true
    try {
        let res = await getUsersListApi(fetchTableListParam)
        // console.log(isSearch)

        tableData.value = res.data.data

        //拼接一个switchLoading字段到数据中

        tableData.value.forEach(item => {
            item.switchLoading = false
        })

        tableLoading.value = false;
        //分页总数
        total.value = res.data.total

    } catch (e) {
        tableLoading.value = false;
    }
}

//在组件加载的时候调用

onMounted(() => {
    getUsersList()


})

//变更用户状态

let changeUserStatus = async (row) => {
    // console.log(row)
    //打开loading
    row.switchLoading = true
    try {
        await updateUserApi({ unid: row.unid, status: row.status })
        row.switchLoading = false
        if (row.status === '1') {
            ElMessage.success(row.username + "用户已启用")
        } else {
            ElMessage.error(row.username + "用户已禁用")
        }

    } catch (e) {
        console.log(e)
        row.switchLoading = false
    }
}


//声明角色选择的变量

let roleOptions = ref([])

//声明选中角色的v-model变量

let selectRoleid = ref("5")

//分配的用户名

let targetUsername = ref("")

//分配的用户unid

let unid = ref("");



//分配角色

let assignmentRole = async (row) => {
    //调用roleStore中方法,重新拉取所有的角色
    roleStore.getAllRoles();
    // console.log(roleStore.allRoles)
    // console.log(row)

    //修改展示的用户名信息

    targetUsername.value = row.username

    unid.value = row.unid;

    //开始处理数据,对于没有权限分配的选项我们要添加disabled属性

    roleOptions.value = roleStore.allRoles.map(role => {
        //这步的目的是为了不去修改store中的原始对象,以免对其它的数据造成影响
        let roleObj = {}
        //获取当前登入用户的角色id
        let currentRoleid = userStore.userInfo.value.roleid;
        // console.log('-----226',currentRoleid)
        // console.log('------227',role.roleid)
        //对比 哪些角色是当前角色自己角色,因为只能分配自己角色
        let flag = isChild(currentRoleid, role.roleid, roleStore.allRoles);
        // console.log(flag)

        roleObj = { ...role }

        if (!flag) {
            //不是自己的子级,添加disabled禁用
            roleObj.disabled = true;
        }

        return roleObj
    }).sort((a, b) => {
        if (a.disabled && !b.disabled) {
            return -1
        }
    })



    // console.log(roleOptions.value)


    //控制dialog打开
    showDialog.value = true
    // try {
    //     let res = await roleApi.assignmentRoleApi()
    //     console.log(res)
    // } catch (e) {

    // }
}

//分配角色的dialog弹窗点取消按钮或者确定按钮的方法

let handleAssignmentConfirm = async () => {
    console.log(unid.value)
    console.log(selectRoleid.value)
    try {
        await roleApi.assignmentRoleApi({ unid: unid.value, roleid: selectRoleid.value })
        let msg = `给${targetUsername.value}分配角色成功`
        ElMessage.success(msg)
        //更新列表
        getUsersList()
    } catch (e) {
        console.log(e)
        ElMessage.error("分配角色失败:" + e.toString())
    }
    showDialog.value = false;
}

let handleAssignmentCancel = () => {
    showDialog.value = false
}

//用户编辑模块

let showEditDialog = ref(false)

//打开弹窗
let reviewData = ref({}) //回显的数据
let openEditDialog = (row) => {
    showEditDialog.value = true
    reviewData.value = row;
    action.value = 'edit'
    title.value = '编辑用户'
    // console.log(row)
}

//点击确定后更新信息

let action = ref("edit")

let updateUser = async (newData) => {
    if (action.value == 'edit') {
        try {
            await updateUserApi(newData);
            ElMessage.success("更新用户信息成功")
            //更新列表
            getUsersList()
        } catch (e) {
            ElMessage.error("更新用户信息失败:" + e.toString())
        }
    } else if (action.value = 'add') {
        try {
            await addUserApi(newData);
            getUsersList()//更新列表
            ElMessage.success("添加用户信息成功")
        } catch (e) {
            ElMessage.error("添加用户信息失败:" + e.toString())
        }
    }
}

//添加用户
let title = ref('添加用户')

let addUser = async () => {
    action.value = 'add'
    title.value = '添加用户'
    showEditDialog.value = true;
}

//分页初始参数

let fetchTableListParam = reactive({
    order_by: -1,
    page: 1,
    count: 7,
    class: "",
    username: ""
})

//分页总数

let total = ref(10)

//搜索填充选项

let searchOptions = ref([])


//分页改变的时候
let handlePageSizeChange = (page) => {
    console.log('pagechange---', page)
    // console.log(value)
    console.log('handlePageSizeChange')
    fetchTableListParam.page = page;
    // console.log('isSearch---',isSearch)
    // console.log('searchText---', searchText.value)
    if (searchText == "") {
        //搜索状态,显示搜索结果的分页
    } else {
        //需要重新向服务器获取新的表格数据
        getUsersList(fetchTableListParam)
    }
}

//搜索绑定的变量

let searchText = ref("");


//远程搜索方法

let handleSearch = async (val) => {
    // console.log('---vale', val)
    searchLoading.value = true;
    if (val != '') {
        //搜索的关键字是username
        fetchTableListParam.username = val;
        //分页默认从第一页开始
        fetchTableListParam.page = 1;
        try {
            let res = await getUsersListApi(fetchTableListParam);
            searchOptions.value = res.data.data
            searchLoading.value = false;
        } catch (e) {
            searchLoading.value = false;
            ElMessage.error("搜索失败:" + e.toString())
        }
    }

}

//选中值发生改变
let searchChange = (val) => {
    fetchTableListParam.username = val;
    getUsersList()
    // console.log(val)
}

//搜索框获得焦点

let handleSearchInputFocus = (val) => { }

//搜索Loading

let searchLoading = ref(false)

//删除用户

let deleteUser = (row) => {
    // console.log(row)
    ElMessageBox.confirm(h('p', [
        h('span', '此操作将永久删除 '),
        h('span', { style: 'color:red;font-size:18px' }, row.username),
        h('span', ' 用户, 是否继续?')
    ]), '⚠️警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: async (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true;
                instance.confirmButtonText = '正在删除...';
                try {
                    await deleteUserApi({ unid: row.unid })
                    ElMessage.success("删除用户成功")
                    getUsersList()
                    done()
                } catch (e) {
                    ElMessage.error("删除用户失败:" + e.toString())
                    done()
                }
            } else {
                done();
            }
        }
    })
}

</script>
<style scoped>
.users :deep(.el-dialog__body) {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.select-user {
    margin: 20px;
    font-size: 18px;
}

.select-user .el-tag {
    font-size: 18px;
    margin-left: 10px;
}

.el-pagination {
    justify-content: center;
    margin-top: 20px;
}

.search {
    margin: 20px 0px;
}

.search :deep(.el-input__wrapper) {
    width: 40vh;
}

.collaction {
    margin-bottom: 20px;
    border: 1px solid #dcdfe6;
    padding: 20px;
    border-radius: 10px;
}
</style>